package pl.edu.pw.MidEmu.UI.Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;

import pl.edu.pw.MidEmu.Base.Controllers.BaseController;
import pl.edu.pw.MidEmu.Common.Consts;
import pl.edu.pw.MidEmu.Common.Models.EthernetInterfaceModel;
import pl.edu.pw.MidEmu.Logic.ProcessHandler;
import pl.edu.pw.MidEmu.Logic.RuleWriter;
import pl.edu.pw.MidEmu.UI.Views.NetworkConnectivityView;

/**
 * Controller for managing network connectivity
 * @author Mateusz Starodab
 *
 */
public class NetworkConnectivityController extends BaseController<NetworkConnectivityView> implements ActionListener
{
	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() instanceof JButton)
		{
			JButton button = (JButton) e.getSource();
			if (button.getName() == Consts.NetworkConnectivity_ButtonOK)
			{
				getView().dispose();
			}
		}
		else if (e.getSource() instanceof JCheckBox)
		{
			JCheckBox box = (JCheckBox) e.getSource();
			String[] ifaces = box.getName().split("_");
			if (box.getModel().isSelected())
			{
				if (ifaces[0].equals("0.0.0.0/0"))
				{
					ProcessHandler h = new ProcessHandler("./data/enableSelf " + ifaces[1], "", "");
					h.start();
					
					RuleWriter.RemoveRule(ifaces[1], ifaces[1]);
				}
				else
				{
					RuleWriter.RemoveRule(ifaces[0], ifaces[1]);
				}
				getView().setConnection(box.getName(), true);
				ProcessHandler h = new ProcessHandler("./data/enableRoute " + ifaces[0] + " " + ifaces[1], "", "");
				h.start();
			}
			else
			{
				if (ifaces[0].equals("0.0.0.0/0"))
				{
					ProcessHandler h = new ProcessHandler("./data/disableSelf " + ifaces[1], "", "");
					h.start();
					
					RuleWriter.AddRule(ifaces[1], ifaces[1]);
				}
				else
				{
					RuleWriter.AddRule(ifaces[0], ifaces[1]);
				}
				getView().setConnection(box.getName(), false);
				ProcessHandler h = new ProcessHandler("./data/disableRoute " + ifaces[0] + " " + ifaces[1], "", "");
				h.start();
			}
		}
	}

	public List<EthernetInterfaceModel> getEthernetInterfaces()
	{
		return getView().getRegisteredInterfaces();
	}
}
